package com.snj.visangedu;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.aocate.presto.service.IDeathCallback_0_8;
import com.aocate.presto.service.IOnBufferingUpdateListenerCallback_0_8;
import com.aocate.presto.service.IOnCompletionListenerCallback_0_8;
import com.aocate.presto.service.IOnErrorListenerCallback_0_8;
import com.aocate.presto.service.IOnInfoListenerCallback_0_8;
import com.aocate.presto.service.IOnPitchAdjustmentAvailableChangedListenerCallback_0_8;
import com.aocate.presto.service.IOnPreparedListenerCallback_0_8;
import com.aocate.presto.service.IOnSeekCompleteListenerCallback_0_8;
import com.aocate.presto.service.IOnSpeedAdjustmentAvailableChangedListenerCallback_0_8;
import com.aocate.presto.service.IPlayMedia_0_8;
import com.google.zxing.client.android.Intents;
import com.snj.visangedu.drm.DRMINFO;
import com.snj.visangedu.drm.VideoAct;
import com.snj.visangedu.homestudy.HomeStudyFragment;
import com.snj.visangedu.homestudy.TeacherFragment;
import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.lib.MyCameraSurface;
import com.snj.visangedu.lib.PopupType;
import com.snj.visangedu.lib.StudyviewFragment;
import com.snj.visangedu.listeningmax.EnglishListeningFragment;
import com.snj.visangedu.listeningmax.ListeningmaxFragment;
import com.snj.visangedu.listeningmax.MP_FileManager;
import com.snj.visangedu.studytime.StopwatchFragment;
import com.snj.visangedu.studytime.StudyPlannerFragment;
import com.snj.visangedu.studytime.StudyTimeFragment;
import com.snj.visangedu.studytime.StudyTimerFragment;
import com.snj.visangedu.video.VideoActivity;
import com.softchips.prestissimo.SoundService;
import com.teruten.tms4encrypt.TMS4Encrypt;
import com.teruten.tms4webserver.TMS4WebServer;
import com.unity3d.player.UnityPlayer;

public class HomeActivity extends FragmentActivity implements OnClickListener
{
	protected UnityPlayer mUnityPlayer;		// don't change the name of this variable; referenced from native code
	
	private final int SEND_ASK	= 0x5150;
	private String TAG = "HomeActivity";
	
	VideoView _video = null;
	private TMS4WebServer _webServer;
	

	private final static int ACTION_ZXING_SCANNER = 0x0000c0de; //IntentIntegrator.REQUEST_CODE
	Button btn = null;
	TextView txt_format, txt_content;
	
	private int currentFragment = R.id.main_img_menu1;
	
	private ImageView mBtnMenuNews;
	private ImageView mBtnMenu2;
	private ImageView mBtnMenu3;	
	private ImageView mBtnMenuMypage;
	private ImageView mBtnMenu5;
	
	private ImageView mBtnSubMenu0_0 = null;
	private ImageView mBtnSubMenu0_1 = null;
	private ImageView mBtnSubMenu0_2 = null;
	private ImageView mBtnSubMenu0_3 = null;
	private ImageView mBtnSubMenu0_4 = null;
	
	private ImageView mBtnSubMenu1_0 = null;
	private ImageView mBtnSubMenu1_1 = null;
	private ImageView mBtnSubMenu1_2 = null;
	private ImageView mBtnSubMenu1_3 = null;
	
	
	private ImageView img_mybox = null;
	
	private LinearLayout lily_submenu0 = null;
	private LinearLayout lily_submenu1 = null;
	private LinearLayout lily_submenu_listeningmax = null;
	
	private Fragment prevFrag = null;
	private String prevFragName = "";
	
	private Fragment mFragEmpty;
	private Fragment mFragHome;
	private Fragment mFragSnu;
	private Fragment mFragConsult;
	private Fragment mFragClinic;
	private Fragment mFragGps;
	private Fragment mFragMenu2;
	private Fragment mFragEdumax;
	private Fragment mFragHomestudy;
	private Fragment mFragTeacher;
	
	private Fragment mFragStopwatch;
	private Fragment mFragStudyTimer;
	private Fragment mFragStudyTime;
	private Fragment mFragStudyPlanner;
	private Fragment mFragSecretPlanner;
	
	private Fragment mFragListeningmax;
	private Fragment mFragFolder;
	private Fragment mFragEnglishListening;
	
	private Fragment mFragPayment;
	private Fragment mFragSkyPayment;
	private Fragment mFragMybox;
	
	private RelativeLayout rlly_backpopup = null;
	private ImageView img_popup_studyplanner = null;
	private ImageView img_popup_glue = null;
	private ImageView img_popup_listeningmax = null;
	private ImageView img_popup_asksent = null;
	private ImageView img_popup_payment_complete = null;
	private ImageView img_popup_resumesent = null;
	private ImageView img_popup_network = null;
	private RelativeLayout rlly_popup_yourphone = null;
	private EditText edt_popup_yourphone = null;
	private Button btn_popup_yourphone = null;
	private ImageView img_popup_request = null;
	
	private RelativeLayout rlly_backpopupcontent = null;
	private LinearLayout lily_isquit = null;
	
	private ImageView img_isquit_yes = null;
	private ImageView img_isquit_no = null;
	
	
	private ImageView img_listeningmax = null;
	private ImageView img_englishlistening = null;
	
	
	public static TextView txt_prevsong = null;
	
	
	private AlertDialog alertIsp; 	
	
	
	ImageButton mBtnX = null;
	public RelativeLayout rlly_popup = null;
	RelativeLayout rlly_popupcontent = null;
	
	public static HomeActivity Instance;
	
	public IPlayMedia_0_8.Stub binder;
	public boolean bMusicComplete, bMusicPrepared;
	
	private boolean listening_edumax = false;
	
	public SharedPreferences settings;
	
	public int deviceWidth, deviceHeight;
	
	public MyCameraSurface mSurface;
	String mRootPath;
	static final String PICFOLDER = "CameraTest";
	
	
	ProgressDialog mDlg = null;
	DRMINFO _info = DRMINFO.getInstance();
	
	private ServiceConnection conn = new ServiceConnection() {

	    @SuppressLint("SdCardPath")
	    @Override
	    public void onServiceConnected(ComponentName arg0, final IBinder arg1) {
	      // TODO Auto-generated method stub
	      binder = (IPlayMedia_0_8.Stub) arg1;
	      try {
	        binder.startSession(new IDeathCallback_0_8() {

	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub

	            return (IPlayMedia_0_8.Stub) arg1;
	          }
	        });
	        binder.registerOnPreparedCallback(0, new IOnPreparedListenerCallback_0_8() {

	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub
	            return (IPlayMedia_0_8.Stub) arg1;
	          }

	          @Override
	          public void onPrepared() throws RemoteException {
	            // TODO Auto-generated method stub
	            Log.d(TAG, "registerOnPreparedCallback, onPrepared");
	            bMusicPrepared = true;
	          }
	        });
	        binder.registerOnCompletionCallback(0, new IOnCompletionListenerCallback_0_8() {

	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub
	            return (IPlayMedia_0_8.Stub) arg1;
	          }

	          @Override
	          public void onCompletion() throws RemoteException {
	            // TODO Auto-generated method stub
	            Log.d(TAG, "registerOnCompletionCallback, onCompletion");
	            binder.reset(0);
	            bMusicComplete = true;

	            // if (CalendarSample.Instance.bNextPlay) CalendarSample.Instance.onMusicNextPlay();
	          }
	        });
	        binder.registerOnPitchAdjustmentAvailableChangedCallback(0,
	            new IOnPitchAdjustmentAvailableChangedListenerCallback_0_8() {

	              @Override
	              public IBinder asBinder() {
	                // TODO Auto-generated method stub
	                return (IPlayMedia_0_8.Stub) arg1;
	              }

	              @Override
	              public void onPitchAdjustmentAvailableChanged(boolean arg0) throws RemoteException {
	                // TODO Auto-generated method stub
	                Log.d(TAG,
	                    "registerOnPitchAdjustmentAvailableChangedCallback, onPitchAdjustmentAvailableChanged");
	              }
	            });
	        binder.registerOnBufferingUpdateCallback(0, new IOnBufferingUpdateListenerCallback_0_8() {

	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub
	            return (IPlayMedia_0_8.Stub) arg1;
	          }

	          @Override
	          public void onBufferingUpdate(int arg0) throws RemoteException {
	            // TODO Auto-generated method stub
	            Log.d(TAG, "registerOnBufferingUpdateCallback : " + arg0);
	          }
	        });
	        binder.registerOnSpeedAdjustmentAvailableChangedCallback(0,
	            new IOnSpeedAdjustmentAvailableChangedListenerCallback_0_8() {

	              @Override
	              public IBinder asBinder() {
	                // TODO Auto-generated method stub
	                return (IPlayMedia_0_8.Stub) arg1;
	              }

	              @Override
	              public void onSpeedAdjustmentAvailableChanged(boolean arg0) throws RemoteException {
	                // TODO Auto-generated method stub
	                Log.d(TAG, "registerOnSpeedAdjustmentAvailableChangedCallback : " + arg0);
	              }
	            });
	        binder.registerOnErrorCallback(0, new IOnErrorListenerCallback_0_8() {

	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub
	            return (IPlayMedia_0_8.Stub) arg1;
	          }

	          @Override
	          public boolean onError(int arg0, int arg1) throws RemoteException {
	            // TODO Auto-generated method stub
	            //Toast.makeText(HomeActivity.this, "error", Toast.LENGTH_LONG).show();
	            return false;
	          }
	        });

	        binder.registerOnSeekCompleteCallback(0, new IOnSeekCompleteListenerCallback_0_8() {
	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub
	            return (IPlayMedia_0_8.Stub) arg1;
	          }

	          @Override
	          public void onSeekComplete() throws RemoteException {
	            // TODO Auto-generated method stub
	            Log.d(TAG, "onSeekComplete");
	            // Log.d(TAG, "onSeekComplete : " + binder.getCurrentPosition(0));
	          }
	        });

	        binder.registerOnInfoCallback(0, new IOnInfoListenerCallback_0_8() {

	          @Override
	          public IBinder asBinder() {
	            // TODO Auto-generated method stub
	            return null;
	          }

	          @Override
	          public boolean onInfo(int arg0, int arg1) throws RemoteException {
	            // TODO Auto-generated method stub
	            Log.d(TAG, "onInfo " + arg0 + " , " + arg1);
	            return false;
	          }

	        });

	      } catch (RemoteException e) {
	        Log.e(TAG, e.getMessage());
	      }

	    }

	    @Override
	    public void onServiceDisconnected(ComponentName arg0) {
	      // TODO Auto-generated method stub
	      Log.d(TAG, "onServiceDisconnected" + arg0.toString());
	    }
	  };
	
	// Setup activity layout
	@Override protected void onCreate (Bundle savedInstanceState)
	{
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		
		Instance = this;
		ScreenInfo();
		init_widget();
		
		// Fragment 
		
		try {
		      Intent intent = new Intent(this, SoundService.class);
		      boolean result = bindService(intent, conn, Context.BIND_AUTO_CREATE);

		      Log.d(TAG, "bind result : " + result);

		    } catch (Exception e) {
		      Log.e(TAG, e.getMessage());
		    }

		    settings = getPreferences(MODE_PRIVATE);
		
		mFragStudyTimer = new StudyTimerFragment();
		
			
		_video = (VideoView)findViewById(R.id.videoView1);
		MediaController mc = new MediaController(this);
		_video.setMediaController(mc);
		
		_video.setOnCompletionListener(new OnCompletionListener() {

			public void onCompletion(MediaPlayer mp) {
				Log.e("VideoAct", "completion."); 
			}
		});
		_video.setOnErrorListener(new OnErrorListener() {

			public boolean onError(MediaPlayer mp, int what, int extra) {
				Log.e("VideoAct", "error.");
				return false;
			}
		});
		
		
		if (savedInstanceState == null) {
			ChagneFragment(mFragStudyTimer);
			Global.PrevFragment = Global.CurrentFragment;
			Log.d(TAG, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
			Global.CurrentFragment = StudyviewFragment.StudyTimerFragment;
		}
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("com.snj.visangedu.edumax.bell");


		mSurface = (MyCameraSurface)findViewById(R.id.previewFrame);
	
		setDeviceData();
		
		
		File edumaxfile = new File(Global.ex_storage + "/visangedu/bf.MS4");
			
		if(!edumaxfile.exists())
		{	
			startDownload_EdumaxAudio();
			Log.d(TAG, "Start downloading");
		}
	}
	
	AutoFocusCallback mAutoFocus = new AutoFocusCallback() {
 		public void onAutoFocus(boolean success, Camera camera) {
 			//mShutter.setEnabled(success);
 			//mSurface.mCamera.takePicture(null, null, mPicture);

 		}
 	};
	
	private void init_widget() {
		
		mBtnMenuNews	= (ImageView)findViewById(R.id.main_img_menu1);
		mBtnMenu2	= (ImageView)findViewById(R.id.main_img_menu2);
		mBtnMenu3	= (ImageView)findViewById(R.id.main_img_menu3);
		mBtnMenuMypage = (ImageView)findViewById(R.id.main_img_menu4);
		mBtnMenu5	= (ImageView)findViewById(R.id.main_img_menu5);
		
		mBtnSubMenu0_0 = (ImageView)findViewById(R.id.img_submenu0_0);
		mBtnSubMenu0_1 = (ImageView)findViewById(R.id.img_submenu0_1);
		mBtnSubMenu0_2 = (ImageView)findViewById(R.id.img_submenu0_2);
		mBtnSubMenu0_3 = (ImageView)findViewById(R.id.img_submenu0_3);
		mBtnSubMenu0_4 = (ImageView)findViewById(R.id.img_submenu0_4);
		
		mBtnSubMenu1_0 = (ImageView)findViewById(R.id.img_submenu1_0);
		mBtnSubMenu1_1 = (ImageView)findViewById(R.id.img_submenu1_1);
		mBtnSubMenu1_2 = (ImageView)findViewById(R.id.img_submenu1_2);
		mBtnSubMenu1_3 = (ImageView)findViewById(R.id.img_submenu1_3);
		
		mBtnSubMenu0_0.setSelected(true);
		mBtnSubMenu0_0.setOnClickListener(this);
		mBtnSubMenu0_1.setOnClickListener(this);
		mBtnSubMenu0_2.setOnClickListener(this);
		mBtnSubMenu0_3.setOnClickListener(this);
		mBtnSubMenu0_4.setOnClickListener(this);
		
		mBtnSubMenu1_0.setOnClickListener(this);
		mBtnSubMenu1_1.setOnClickListener(this);
		mBtnSubMenu1_2.setOnClickListener(this);
		mBtnSubMenu1_3.setOnClickListener(this);
		
		
		lily_submenu0 = (LinearLayout)findViewById(R.id.lily_submenu0);
		lily_submenu1 = (LinearLayout)findViewById(R.id.lily_submenu1);
		lily_submenu_listeningmax = (LinearLayout)findViewById(R.id.lily_submenu_listeningmax);
		
		mBtnMenuNews.setOnClickListener(this);
		mBtnMenu2.setOnClickListener(this);
		mBtnMenu3.setOnClickListener(this);		
		mBtnMenuMypage.setOnClickListener(this);
		mBtnMenu5.setOnClickListener(this);
		
		mBtnMenuNews.setSelected(true);
		
		mBtnX = (ImageButton)findViewById(R.id.imgbtn_x);
		mBtnX.setOnClickListener(this);
		
		rlly_popup = (RelativeLayout)findViewById(R.id.rlly_popup);
		rlly_popupcontent = (RelativeLayout)findViewById(R.id.rlly_popcontent);
		
		rlly_backpopup = (RelativeLayout)findViewById(R.id.rlly_backpopup);
		rlly_backpopupcontent = (RelativeLayout)findViewById(R.id.rlly_backpopupcontent);
		img_popup_studyplanner = (ImageView)findViewById(R.id.img_popup_studyplanner);
		img_popup_glue = (ImageView)findViewById(R.id.img_popup_glue);
		img_popup_listeningmax = (ImageView)findViewById(R.id.img_popup_listeningmax);
		img_popup_asksent = (ImageView)findViewById(R.id.img_popup_asksent);
		img_popup_payment_complete = (ImageView)findViewById(R.id.img_popup_paymentcomplete);
		img_popup_resumesent = (ImageView)findViewById(R.id.img_popup_resumesent);
		rlly_popup_yourphone = (RelativeLayout)findViewById(R.id.rlly_popup_yourphone);
		edt_popup_yourphone = (EditText)findViewById(R.id.edt_popup_yourphone);
		btn_popup_yourphone = (Button)findViewById(R.id.btn_popup_yourphone);
		btn_popup_yourphone.setOnClickListener(this);
		img_popup_request = (ImageView)findViewById(R.id.img_popup_request);
		img_popup_network = (ImageView)findViewById(R.id.img_popup_network);
		
		lily_isquit = (LinearLayout)findViewById(R.id.lily_isquit);
		img_isquit_yes = (ImageView)findViewById(R.id.img_isquit_yes);
		img_isquit_no = (ImageView)findViewById(R.id.img_isquit_no);
		
		img_isquit_yes.setOnClickListener(this);
		img_isquit_no.setOnClickListener(this);
		
		img_mybox = (ImageView)findViewById(R.id.img_mybox);
		img_mybox.setOnClickListener(this);
		
		
		img_listeningmax = (ImageView)findViewById(R.id.img_listeningmax);
		img_englishlistening = (ImageView)findViewById(R.id.img_englishlistening);
		
		
		img_listeningmax.setOnClickListener(this);
		img_englishlistening.setOnClickListener(this);
		
	}
	
	private void startZxingScanner() {
	    final Intent intent = new Intent(this, com.google.zxing.client.android.CaptureActivity.class);
	    intent.setAction(Intents.Scan.ACTION);
	    startActivityForResult(intent, ACTION_ZXING_SCANNER);
	}
	
	private void ChagneFragment(Fragment frag) {
		
		if(!Global.isNetworkStat(this))
	    {
	    	//rlly_popup.setVisibility(View.VISIBLE);
			Show_Popup(PopupType.NetworkError);
	    	new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					//HomeActivity.this.finish();
					
				}
			}, 5000);
	    	
	    	return;
	    }
		
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		
		
		if(prevFrag != null)
			ft.remove(prevFrag);
		
		ft.replace(R.id.main_layout_frame, frag);
		prevFrag = frag;
		ft.commit();
		
		
	}
	
	@Override
	public void onClick(View v) {
		
		if(v.getId() == currentFragment) return;
		
		
		Log.d(TAG, "id : " + v.getId());
		switch(v.getId()) {
		case R.id.main_img_menu1:	
			
			Log.d(TAG, "Studytime clicked");
			mBtnMenuNews.setSelected(true);
			mBtnMenu2.setSelected(false);		
			mBtnMenu3.setSelected(false);	
			mBtnMenuMypage.setSelected(false);
			mBtnMenu5.setSelected(false);
			lily_submenu0.setVisibility(View.VISIBLE);
			lily_submenu1.setVisibility(View.GONE);
			lily_submenu_listeningmax.setVisibility(View.GONE);
			
			mBtnSubMenu0_0.setSelected(true);
			
			Log.d(TAG, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
			if(Global.CurrentFragment != StudyviewFragment.StudyTimerFragment)
			{
				ChagneFragment(mFragStudyTimer);
				//Log.d(TAG, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.StudyTimerFragment;
			}
			
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(false);
			mBtnSubMenu0_4.setSelected(false);
			
			mBtnSubMenu1_0.setSelected(false);
			mBtnSubMenu1_1.setSelected(false);
			mBtnSubMenu1_2.setSelected(false);
			
			currentFragment = R.id.main_img_menu1;
			break;
		case R.id.main_img_menu2:	
			
			Log.d(TAG, "magazine onClick");
			mBtnMenuNews.setSelected(false);
			mBtnMenu2.setSelected(true);		
			mBtnMenu3.setSelected(false);	
			mBtnMenuMypage.setSelected(false);
			mBtnMenu5.setSelected(false);
			lily_submenu0.setVisibility(View.GONE);
			lily_submenu1.setVisibility(View.VISIBLE);
			lily_submenu_listeningmax.setVisibility(View.GONE);
			
			mBtnSubMenu1_0.setSelected(true);
			if(Global.CurrentFragment != StudyviewFragment.HomeFragment)
			{
				if(mFragHome == null)
					mFragHome = new NewsFragment(0);
				ChagneFragment(mFragHome);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.HomeFragment;
			}
			currentFragment = R.id.main_img_menu2;
			
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(false);
			
			
			mBtnSubMenu1_1.setSelected(false);
			mBtnSubMenu1_2.setSelected(false);
			
			break;			
		case R.id.main_img_menu3:
			
			if(Global.ispaid)
			{
				open_videowindow("edumax");
				break;
			}
			mBtnMenuNews.setSelected(false);
			mBtnMenu2.setSelected(false);		
			mBtnMenu3.setSelected(true);	
			mBtnMenuMypage.setSelected(false);
			mBtnMenu5.setSelected(false);
			lily_submenu0.setVisibility(View.GONE);
			lily_submenu1.setVisibility(View.GONE);
			lily_submenu_listeningmax.setVisibility(View.GONE);
			
			if(Global.CurrentFragment != StudyviewFragment.EdumaxFragment)
			{
				if(mFragEdumax == null)
					mFragEdumax = new EdumaxFragment();
				ChagneFragment(mFragEdumax);
				
				//Log.d(tag, "CurrentFragment : " + Global.CurrentFragment);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.EdumaxFragment;
			}
			
			currentFragment = R.id.main_img_menu3;		
			//startZxingScanner();
			break;
		
		case R.id.main_img_menu4:
			
			mBtnMenuNews.setSelected(false);
			mBtnMenu2.setSelected(false);		
			mBtnMenu3.setSelected(false);	
			mBtnMenuMypage.setSelected(true);
			mBtnMenu5.setSelected(false);
			lily_submenu0.setVisibility(View.GONE);
			lily_submenu1.setVisibility(View.GONE);
			
			Log.d(TAG, "level : " + Global.level);
			if(Global.level >= 7)
			{
				Log.d(TAG, "선생님 모드");
				if(Global.CurrentFragment != StudyviewFragment.TeacherFragment)
				{
					if(mFragTeacher == null)
					{
						mFragTeacher = new TeacherFragment();
					}
					
					ChagneFragment(mFragTeacher);
					Global.CurrentFragment = StudyviewFragment.TeacherFragment;
				}
			}
			else
			{
				if(Global.CurrentFragment != StudyviewFragment.HomestudyFragment)
				{
					if(mFragHomestudy == null)
					{
						mFragHomestudy = new HomeStudyFragment();
					}
					ChagneFragment(mFragHomestudy);
					Global.CurrentFragment = StudyviewFragment.HomestudyFragment;
				}
			}
			
			currentFragment = R.id.main_img_menu4;
			
			mSurface.mCamera.autoFocus(mAutoFocus);
			
			break;
		case R.id.main_img_menu5: 
			
			Log.d(TAG, "listening max clicked");
			
	
			
			mBtnMenuNews.setSelected(false);
			mBtnMenu2.setSelected(false);		
			mBtnMenu3.setSelected(false);	
			mBtnMenuMypage.setSelected(false);
			mBtnMenu5.setSelected(true);
			
			//img_popup_listeningmax.setVisibility(View.VISIBLE);
			img_popup_studyplanner.setVisibility(View.GONE);
			img_popup_glue.setVisibility(View.GONE);
			//rlly_popup.setVisibility(View.VISIBLE);
			//rlly_popup.invalidate();
			
			lily_submenu0.setVisibility(View.GONE);
			lily_submenu1.setVisibility(View.GONE);
			lily_submenu_listeningmax.setVisibility(View.VISIBLE);
			
			
			if(Global.CurrentFragment != StudyviewFragment.ListeningmaxFragment)
			{
				
				if(mFragListeningmax == null)
				{
					mFragListeningmax = new ListeningmaxFragment();
				}
				
				ChagneFragment(mFragListeningmax);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.ListeningmaxFragment;
			}
			
			currentFragment = R.id.main_img_menu2;
			
			img_listeningmax.setSelected(true);
			img_englishlistening.setSelected(false);
			
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(false);
			
			
			mBtnSubMenu1_1.setSelected(false);
			mBtnSubMenu1_2.setSelected(false);
			
			currentFragment = R.id.main_img_menu5;
			break;
			
		case R.id.img_submenu0_0:
			//Log.d(tag, "sub0_0");
			mBtnSubMenu0_0.setSelected(true);
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(false);
			mBtnSubMenu0_4.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.StudyTimerFragment)
			{
				ChagneFragment(mFragStudyTimer);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.StudyTimerFragment;
			}
			else
			{
				((StudyTimerFragment)mFragStudyTimer).ClosePopup();
			}
			break;
		case R.id.img_submenu0_1:
			//Log.d(tag, "sub0_1");
			mBtnSubMenu0_0.setSelected(false);
			mBtnSubMenu0_1.setSelected(true);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(false);
			mBtnSubMenu0_4.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.StopwatchFragment)
			{
				if(mFragStopwatch == null)
					mFragStopwatch = new StopwatchFragment();
				ChagneFragment(mFragStopwatch);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.StopwatchFragment;
			}
			break;
		case R.id.img_submenu0_2:
			
			mBtnSubMenu0_0.setSelected(false);
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(true);
			mBtnSubMenu0_3.setSelected(false);
			mBtnSubMenu0_4.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.StudyPlannerFragment)
			{
				if(mFragStudyPlanner == null)
					mFragStudyPlanner = new StudyPlannerFragment();
				ChagneFragment(mFragStudyPlanner);
				Global.CurrentFragment = StudyviewFragment.StudyPlannerFragment;
			}
			break;
		case R.id.img_submenu0_3:
			//Log.d(tag, "sub0_3");
			mBtnSubMenu0_0.setSelected(false);
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(true);
			mBtnSubMenu0_4.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.StudyTimeFragment)
			{
				if(mFragStudyTime == null)
					mFragStudyTime = new StudyTimeFragment();
				ChagneFragment(mFragStudyTime);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.StudyTimeFragment;
			}
			break;
		case R.id.img_submenu0_4:
			//Log.d(tag, "sub0_4");
			mBtnSubMenu0_0.setSelected(false);
			mBtnSubMenu0_1.setSelected(false);
			mBtnSubMenu0_2.setSelected(false);
			mBtnSubMenu0_3.setSelected(false);
			mBtnSubMenu0_4.setSelected(true);
			if(Global.CurrentFragment != StudyviewFragment.SecretPlannerFragment)
			{
				if(mFragSecretPlanner == null)
					mFragSecretPlanner = new NewsFragment(2);
				ChagneFragment(mFragSecretPlanner);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.SecretPlannerFragment;
			} 
			break;
			
		case R.id.img_submenu1_0:		
			mBtnSubMenu1_0.setSelected(true);
			mBtnSubMenu1_1.setSelected(false);
			mBtnSubMenu1_2.setSelected(false);
			mBtnSubMenu1_3.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.HomeFragment)
			{
				if(mFragHome == null)
					mFragHome = new NewsFragment(0);
				ChagneFragment(mFragHome);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.HomeFragment;
			}
			break;
		case R.id.img_submenu1_1:
			mBtnSubMenu1_0.setSelected(false);
			mBtnSubMenu1_1.setSelected(true);
			mBtnSubMenu1_2.setSelected(false);
			mBtnSubMenu1_3.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.SNUFragment)
			{
				if(mFragSnu == null)
					mFragSnu = new NewsFragment(1);
				ChagneFragment(mFragSnu);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.SNUFragment;
			}
			break;
		case R.id.img_submenu1_2:		// 1占쎈쾻疫뀐옙 占쎌뿯占쎈뻻占쎈뱟揶쏉옙
			
			mBtnSubMenu1_0.setSelected(false);
			mBtnSubMenu1_1.setSelected(false);
			mBtnSubMenu1_2.setSelected(true);
			mBtnSubMenu1_3.setSelected(false);
			if(Global.CurrentFragment != StudyviewFragment.ClinicFragment)
			{
				if(mFragClinic == null)
					mFragClinic = new ClinicFragment();
				ChagneFragment(mFragClinic);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.ClinicFragment;
			}
			break;
		case R.id.img_submenu1_3:		// 1占쎈쾻疫뀐옙 占쎌뿯占쎈뻻占쎈뱟揶쏉옙
			
			mBtnSubMenu1_0.setSelected(false);
			mBtnSubMenu1_1.setSelected(false);
			mBtnSubMenu1_2.setSelected(false);
			mBtnSubMenu1_3.setSelected(true);
			if(Global.CurrentFragment != StudyviewFragment.GpsFragment)
			{
				if(mFragGps == null)
					mFragGps = new GpsFragment();
				ChagneFragment(mFragGps);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.GpsFragment;
			}
			break;
		case R.id.imgbtn_x:
			rlly_popup.setVisibility(View.GONE);
			break;
			
		case R.id.img_isquit_yes:
			moveTaskToBack(true);
		     android.os.Process.killProcess(android.os.Process.myPid());
			finish();
			break;			
		case R.id.img_isquit_no:
			//
			rlly_backpopupcontent.setBackgroundResource(R.color.edumax_color);
			rlly_backpopup.setVisibility(View.GONE);
			//rlly_backpopupcontent.setBackgroundColor(Color.BLUE);
			break;
		case R.id.img_mybox:
			
			lily_submenu0.setVisibility(View.GONE);
			lily_submenu1.setVisibility(View.GONE);
			if(Global.CurrentFragment != StudyviewFragment.MyboxFragment)
			{
				if(mFragMybox == null)
					mFragMybox = new Mybox_Fragment();
				ChagneFragment(mFragMybox);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.MyboxFragment;
			}
			
			break;
		case R.id.img_listeningmax:
			img_listeningmax.setSelected(true);
			img_englishlistening.setSelected(false);
			
			
			
			if(Global.CurrentFragment != StudyviewFragment.ListeningmaxFragment)
			{
				if(mFragListeningmax == null)
					mFragListeningmax = new ListeningmaxFragment();
				ChagneFragment(mFragListeningmax);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.ListeningmaxFragment;
			}
			break;
		case R.id.img_englishlistening:
			img_listeningmax.setSelected(false);
			img_englishlistening.setSelected(true);
			
			
			if(Global.CurrentFragment != StudyviewFragment.EnglishListeningFragment)
			{
				if(mFragEnglishListening == null)
					mFragEnglishListening = new EnglishListeningFragment();
				ChagneFragment(mFragEnglishListening);
				//Log.d(tag, "Prev : " + Global.PrevFragment + ", Current : " + Global.CurrentFragment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.EnglishListeningFragment;
			}
			else
			{
				((EnglishListeningFragment)mFragEnglishListening).reinit();
			}
			break;
		case R.id.btn_popup_yourphone:
			//Show_Popup(PopupType.Request);
			SendAsk(edt_popup_yourphone.getText().toString());
			break;
		
		default:
			if(Global.CurrentFragment == StudyviewFragment.StudyPlannerFragment)
			{
				((StudyPlannerFragment)mFragStudyPlanner).onClick(v);
			}
			break;
		}
		
		
	}
	
	public void onMusicFolderMode(View v) {
	    //ChangeMode(enumSubView.H6_MUSIC_FOLDER);
	    if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
	    {
	    	((ListeningmaxFragment)mFragListeningmax).onClick(v);	    	
	    }
	}
	

	public void onMusicPlayMode(View v) {		
		if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
	    {
	    	((ListeningmaxFragment)mFragListeningmax).onClick(v);	    	
	    }
		
	}
	

	public void onMusicFolderDirOpen(View v) {
	  if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
	  {
		  ((ListeningmaxFragment)mFragListeningmax).onMusicFolderDirOpen(v);
	  }
	}

	// �쓬�븙 �뤃�뜑 由ъ뒪�듃�뿉�꽌 file open �겢由��떆 ...
	public void onMusicFolderDirRename(View v) {
		if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
		  {
			  ((ListeningmaxFragment)mFragListeningmax).onMusicFolderDirRename(v);
		  }
	}

	  // play 怨� 由ъ뒪�듃�뿉 異붽� ...
	  public void onMusicFolderFilePlayEntry(View v) {
		  if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
		  {
			  ((ListeningmaxFragment)mFragListeningmax).onMusicFolderFilePlayEntry(v);
		  }
	  }

	  public void onMusicFolderFileRename(View v) {
		  if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
		  {
			  ((ListeningmaxFragment)mFragListeningmax).onMusicFolderFileRename(v);
		  }
	  }

	  // �뵆�젅�씠 �냽�룄 蹂�寃� ...
	  public void onMusicPlaySpeed(View v) {
	    if (bNextPlay) return;

	    if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
		  {
			  ((ListeningmaxFragment)mFragListeningmax).onMusicPlaySpeed(v);
		  }
	  }

	  // play / pause ...
	  public void onMusicPlayStart(View v) {
		  if (bNextPlay) return;
		    Log.d(TAG, "onMusicPlayStart");
		    // hMusicPlayer
		    if (!((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.bPlaySong) {
		      if (MP_FileManager.Instance.songs.size() == 0) {
		        new Handler().postDelayed(new Runnable() {
		          public void run() {
		            Toast.makeText(getApplicationContext(), "곡을 선택하세요.", 1000).show();
		          }
		        }, 100);
		        return;
		      }
		      // 怨� 由ъ뒪�듃�쓽 泥ル쾲吏멸끝 �옱�떛 ...
		      ((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.PlaySong(MP_FileManager.Instance.songs.get(0).snID);
		      return;
		    }

		    ((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.PlayTogglePause();
	  }
	  
	  public void onEdumaxStart(View v) {
		  
		  Log.d(TAG, "onEdumaxStart");
		  if(Global.ispaid)
		  {
			  //startActivity(new Intent(getApplicationContext(), VideoAct.class));
			  if(listening_edumax)
			  {
				  listening_edumax = false;
				  v.setSelected(listening_edumax);
				  StopMedia();
			  }
			  else
			  {
				  listening_edumax = true;
				  v.setSelected(listening_edumax);
				  //PlayMedia("http://studyview.co.kr/ms4/bf.MS4");
			  }
		  }
		  else
		  {
			  Toast.makeText(HomeActivity.this, "유료회원만 제공됩니다.", Toast.LENGTH_LONG).show();
		  }
	  } 

	// part select ...
	  public void onMusicPlayPart(View v) {

		  ((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.EnablePart(!((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.bPartDefine);
	  }

	  // repeat ...
	  public void onMusicPlayRepeat(View v) {
		  
		((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.ToggleLoop();
	  }

	  public boolean bNextPlay = false;
	  public int iNextPlayID;

	  public void onMusicNextPlay() {
		  
		  if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
		  {
			  ((ListeningmaxFragment)mFragListeningmax).onMusicNextPlay();
		  }
	  }
	  
	  

	// snog start
	  public void onMusicPlaySongStart(View v) {
		  ViewGroup vg = null;
		  
		Log.d("onMusicPlaySongStart", "onMusicPlaySongStart, id=" + v.getId());
	    if (bNextPlay)
	    {
	    	Log.d("onMusicPlaySongStart", "bNextPlay = " + bNextPlay);
	    	return; 
	    }

	    ((TextView)v).setTextColor(Color.parseColor("#7DC5F8"));
	    
	    vg = (ViewGroup) ((TextView)v).getParent();
	    	
	    	for(int i=0; i<vg.getChildCount(); i++)
	    	{
	    		if(vg.getChildAt(i) instanceof ImageButton)
	    		{
	    			((ImageButton)vg.getChildAt(i)).setImageResource(R.drawable.music_icon_1);
	    		}
	    	}
	    	
	    if(txt_prevsong != null)
	    	txt_prevsong.setTextColor(Color.parseColor("#808080"));
	    
	    
	    if (((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.bPlaySong) {
	      bNextPlay = true;
	      ((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.PlayStop();
	      
	      //((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.iPlaySongID
	      
	      if(v instanceof TextView)
	      {
	    	  
	    	  if(txt_prevsong != null)
	    	  {
	    		  txt_prevsong.setTextColor(Color.parseColor("#808080"));
	    		  
	    		 vg = (ViewGroup) txt_prevsong.getParent();
	    	    	
	    	    	for(int i=0; i<vg.getChildCount(); i++)
	    	    	{
	    	    		if(vg.getChildAt(i) instanceof ImageButton)
	    	    		{
	    	    			((ImageButton)vg.getChildAt(i)).setImageResource(R.drawable.btn_mp_song_list_del_click);
	    	    		}
	    	    	}
	    	  }
	    	  
	    	  ((TextView)v).setTextColor(Color.parseColor("#7DC5F8"));
	    	  v.setTag("current");
	    	  Log.d("Music_Player", "snID : " + v.getId());
	    	  txt_prevsong = (TextView)v;
	    	  
	    	  vg = (ViewGroup) txt_prevsong.getParent();
  	    	
	  	    	for(int i=0; i<vg.getChildCount(); i++)
	  	    	{
	  	    		if(vg.getChildAt(i) instanceof ImageButton)
	  	    		{
	  	    			((ImageButton)vg.getChildAt(i)).setImageResource(R.drawable.music_icon_1);
	  	    		}
	  	    	}
	    	  
	    	  
	    	  
	      }

	      ((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.iPlaySongID = v.getId();
	      new Handler().postDelayed(new Runnable() {
	        public void run() {
	        	((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.PlaySong(-1);
	        	bNextPlay = false;
	        }
	      }, 500);

	    } else {
	    	((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.PlaySong(v.getId());
	    }
	    
	    txt_prevsong = (TextView)v;
	  }

	  // �뵆�젅�씠 怨� 由ъ뒪�듃�뿉�꽌 �젣嫄� ...
	  public void onMusicPlaySongListDel(View v) {
		  if(Global.CurrentFragment == StudyviewFragment.ListeningmaxFragment)
		  {
			  ((ListeningmaxFragment)mFragListeningmax).onMusicPlaySongListDel(v);
		  }
	  }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == ACTION_ZXING_SCANNER)
		{
			if(resultCode == RESULT_OK)
			{
				String content = data.getStringExtra("SCAN_RESULT");
				
				Intent videointent = new Intent(getApplicationContext(), VideoActivity.class);
				videointent.putExtra("videoid", content);
				startActivity(videointent);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		switch (keyCode) {
		    case KeyEvent.KEYCODE_BACK:
		    	
		    	if(Global.CurrentFragment == StudyviewFragment.StudyTimerFragment)
		    	{
		    		if(((StudyTimerFragment)mFragStudyTimer).ClosePopup() != 0)
		    			return true;
		    	}
		    	else if(Global.CurrentFragment == StudyviewFragment.PayFragment)
		    	{
		    		if(prevFragName == "studytimer")
		    		{
		    			ChagneFragment(mFragStudyTimer);
		    			Global.PrevFragment = Global.CurrentFragment;
						Global.CurrentFragment = StudyviewFragment.StudyTimerFragment;
		    		}
		    		else if(prevFragName == "stopwatch")
		    		{
		    			ChagneFragment(mFragStopwatch);
		    			Global.PrevFragment = Global.CurrentFragment;
						Global.CurrentFragment = StudyviewFragment.StopwatchFragment;
		    		}
		    		else if(prevFragName == "edumax")
		    		{
		    			ChagneFragment(mFragEdumax);
		    			Global.PrevFragment = Global.CurrentFragment;
						Global.CurrentFragment = StudyviewFragment.EdumaxFragment;
		    		}
		    		
		    		prevFragName = "";
		    		return true;
		    	}
		    	else if(Global.CurrentFragment == StudyviewFragment.EnglishListeningFragment)
		    	{
		    		if(((EnglishListeningFragment)mFragEnglishListening).ClosePopup() != 0)
		    			return true;
		    	}
		    	else if(Global.CurrentFragment == StudyviewFragment.SkyPayFragment)
		    	{
		    		ChagneFragment(mFragClinic);
		    		Global.PrevFragment = Global.CurrentFragment;
		    		Global.CurrentFragment = StudyviewFragment.ClinicFragment;
		    		return true;
		    	}
		    	else if(Global.CurrentFragment == StudyviewFragment.ClinicFragment)
		    	{
		    		if(rlly_popup.getVisibility() == View.VISIBLE)
		    		{
		    			rlly_popup.setVisibility(View.GONE);
		    			return true;
		    		}
		    	}
		    	else if(Global.CurrentFragment == StudyviewFragment.TeacherFragment)
		    	{
		    		if(((TeacherFragment)mFragTeacher).ClosePopup() != 0)
		    			return true;
		    	}
		    	
		    	Log.d(TAG, "CurrentFragment : " + Global.CurrentFragment);
		    	
		    	rlly_backpopup.setVisibility(View.VISIBLE);
		    	rlly_backpopupcontent.setBackgroundColor(Color.parseColor("#7DC5F8"));
		    	lily_isquit.setBackgroundColor(Color.parseColor("#FFFFFF"));
		    	rlly_backpopupcontent.setVisibility(View.VISIBLE);
		    	
		    	return true;
		    	
		}


		
		
		return super.onKeyDown(keyCode, event);
	}
	
	public void open_videowindow(String caller)
	{
		prevFragName = caller;
		
		if(mFragEmpty == null)
			mFragEmpty = new Menu0_0Fragment();
		
		startActivity(new Intent(getApplicationContext(), VideoAct.class));
	} 
	
	public void close_videowindow()
	{
		if(prevFragName == "edumax")
		{
			ChagneFragment(mFragEdumax);
			Global.PrevFragment = Global.CurrentFragment;
			Global.CurrentFragment = StudyviewFragment.EdumaxFragment;
		}
	}
	
	public void open_paywindow(String caller)
	{
		prevFragName = caller;
		Runnable open_paywindow_runner = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				if(mFragPayment == null)
				{
					mFragPayment = new Pay_Fragment();
				}
				
				ChagneFragment(mFragPayment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.PayFragment;
			}
		};
		
		open_paywindow_runner.run();
	}
	
	public void open_skypaywindow(String caller)
	{
		prevFragName = caller;
		Runnable open_paywindow_runner = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				if(mFragSkyPayment == null)
				{
					mFragSkyPayment = new SkyPay_Fragment();
				}
				
				ChagneFragment(mFragSkyPayment);
				Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.SkyPayFragment;
			}
		};
		
		open_paywindow_runner.run();
	}
	
	public void close_paywindow()
	{
		Log.d(TAG, "close paywindow : " + prevFragName);
		if(Global.CurrentFragment == StudyviewFragment.PayFragment)
    	{
    		if(prevFragName == "studytimer")
    		{
    			ChagneFragment(mFragStudyTimer);
    			Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.StudyTimerFragment;
    		}
    		else if(prevFragName == "stopwatch")
    		{
    			ChagneFragment(mFragStopwatch);
    			Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.StopwatchFragment;
    		}
    		else if(prevFragName == "edumax")
    		{
    			ChagneFragment(mFragEdumax);
    			Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.EdumaxFragment;
    		}
    		else if(prevFragName == "clinic")
    		{
    			ChagneFragment(mFragClinic);
    			Global.PrevFragment = Global.CurrentFragment;
				Global.CurrentFragment = StudyviewFragment.ClinicFragment;
    		}
    		
    		prevFragName = "";
    	}
		
		
	}
	
	public void PlayMedia(String path)
	{
		if(Global.IsDownloading)
		{
			Toast.makeText(HomeActivity.this, "컨텐츠를 다운로드중입니다", Toast.LENGTH_LONG).show();
			return;
		}
		new AsyncTask<String, String, String>() {

            String strMediaPath1 = "";
            @Override
            protected String doInBackground(String... params) {
                    // TODO Auto-generated method stub
                    
                    strMediaPath1 = params[0];
                    
                    if (strMediaPath1.endsWith(".MS4")) {
                            int nReturn;
                            
                            // �뜝�떗源띿삕�솕
                            DRM_Init();

                            // �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕�뜝�뙣源띿삕 - �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕
                            if (strMediaPath1.startsWith("http://")) {
                                    nReturn = _webServer.OpenRemoteMedia(strMediaPath1);
                                    if(nReturn != TMS4Encrypt.TMS4E_OK)
                                    {
                                            displayMessage("open remote media error : " + nReturn);
                                            return null;
                                    }
                                    else
                                    {
                                            Log.d("VideoAct", "Success");
                                    }
                            }
                            // �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕�뜝�뙣源띿삕 - �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕
                            else 
                            {	
                                    int nTime = (int) (System.currentTimeMillis() / 1000);
                                    int nRtn = TMS4Encrypt.TMS4ERecrypt(strMediaPath1,
                    						_info.HINT, _info.IMEI, _info.MACADDRESS, "user", "url", "watermark",
                    	    				nTime, 30, 0, 7);
                                    Log.d(TAG, "standard time0 : " + nTime);
                                    
                                    Log.d(TAG, "(Local) nRtn : " + nRtn);
                                    nReturn = _webServer.MediaAccreditation(strMediaPath1, nTime);
                                    Log.d(TAG, "(Local) nReturn : " + nReturn);
                                    if (nReturn != 0) {
                                            //displayMessage("open local media error : " + nReturn);
                                    	
                                    		setDeviceData();
                                    		
                                    		int nStandardTime = (int)(System.currentTimeMillis() / 1000);
                                    		Log.d(TAG, "standard time1 : " + nStandardTime);
                            				
                                    		nRtn = TMS4Encrypt.TMS4ERecrypt(strMediaPath1,
                            						_info.HINT, _info.IMEI, _info.MACADDRESS, "user", "url", "watermark",
                            	    				nTime, 30, 0, 7);
                                    		Log.d(TAG, "(Local) nRtn(1) : " + nRtn);
                            				
                            				nTime = (int) (System.currentTimeMillis() / 1000);
                            				Log.d(TAG, "standard time2 : " + nTime);
                            				nReturn = _webServer.MediaAccreditation(strMediaPath1, nTime);
                            				Log.d(TAG, "(Local) nReturn(1) : " + nReturn);
                            				if (nReturn != 0) {
                            					//displayMessage("open local media error : " + nReturn);
                            					Log.d(TAG, "Faile Accredit : " + Integer.toString(nReturn));
                            					return null;
                            				}
                            				//DRM_showInfo();
                                            return null;
                                    }
                                    //DRM_showInfo();
                            }
                            
                            // DRM �뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕�뜝�룞�삕.
                            strMediaPath1 = _webServer.getFilePath(strMediaPath1);
                    }

                    
                    
                    
                    
                    
                    return null;
            }

            @Override
            protected void onPostExecute(String result) {
                    // TODO Auto-generated method stub
                    super.onPostExecute(result);
                    
                    //_video.setVideoURI(Uri.parse(strMediaPath));
                    _video.setVideoPath(strMediaPath1);
                    _video.start();
                    Log.e("VideoAct", "media path : " + strMediaPath1);
            }
            
            
            
            
    }.execute(path);
	}
	
	
	private boolean copyFile(File file , String save_file){
        boolean result;
        if(file!=null&&file.exists()){
            try {
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream newfos = new FileOutputStream(save_file);
                int readcount=0;
                byte[] buffer = new byte[1024];
                while((readcount = fis.read(buffer,0,1024))!= -1){
                    newfos.write(buffer,0,readcount);
                }
                newfos.close();
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            result = true;
        }else{
            result = false;
        }
        return result;
    }
	
	public void StopMedia()
	{
		_video.stopPlayback();
	}

	/**********************************************************
	 * DRM �뜝�룞�삕�뜝�룞�삕 �뜝�뙃�눦�삕
	**********************************************************/
	private void DRM_Init() {
		if (_webServer == null) {
			_webServer = new TMS4WebServer();
			DRMINFO info = DRMINFO.getInstance();
			_webServer.InitInstance(info.IMEI, info.MACADDRESS, this);
			_webServer.StartServer(50000);
		}
	}

	private void DRM_showInfo()
	{
		int nEndTime = _webServer.GetEndTime();
		int nCountPolicy = _webServer.GetPolicyCount();
		int nPolicyType = _webServer.GetPolicyType();

		if (nPolicyType == 0x102) // 기간 정책이 있는 경우.
		{
			Log.d(TAG, "policy type : period");
			if (nEndTime > 0) {
				long lTime = (long) nEndTime * 1000;
				Log.d(TAG, "time : " + Long.toString(lTime) + ", "+ Integer.toString(nEndTime));
				Date date = new Date(lTime);
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
				displayMessage(format.format(date) + " 까지 재생 가능");
			}
		}
		if (nPolicyType == 0x104) // 횟수 정책이 있는 경우.
		{
			if (nCountPolicy > 0) {
				Log.d(TAG, "policy type : count");
				displayMessage("남은 횟수는  " + nCountPolicy + " 회");
			}
		}
		if (nPolicyType == (0x102 | 0x104)) // 기간+횟수 정책이 있는 경우.
		{
			Log.d(TAG, "period + count");
			long lTime = (long) nEndTime * 1000;
			Log.d(TAG, "time : " + Long.toString(lTime) + ", "+ Integer.toString(nEndTime));
			Date date = new Date(lTime);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.KOREA);
			if ((nEndTime > 0) && (nCountPolicy > 0))
				displayMessage(format.format(date) + " 까지 재생 가능하고 "
						+ nCountPolicy + " 회 재생 가능");
		}
	}

	/**********************************************************
	 * 기타 함수
	**********************************************************/
	 // Toast 로 메시지 출력
	public void displayMessage(String message){
		if(message != null){
			Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		
		
		if(Global.PrevFragment == StudyviewFragment.EMPTY || Global.PrevFragment == StudyviewFragment.HomeFragment)
		{
			
		}
		else if(Global.PrevFragment == StudyviewFragment.SNUFragment)
		{
		}else if(Global.PrevFragment == StudyviewFragment.ConsultFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.EdumaxFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.SNU1stFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.StudyTimerFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.StopwatchFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.StudyPlannerFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.StudyTimeFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.SecretPlannerFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.PayFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.MyboxFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.ListeningmaxFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.FolderFragment)
		{
		}
		else if(Global.PrevFragment == StudyviewFragment.EnglishListeningFragment)
		{
		}
		
		if(prevFragName == "edumax")
		{
			//close_videowindow();
		}
	}

	public String GetPrevFragName()
	{
		String temp = prevFragName;
		prevFragName = "";
		return temp;
	}
	
	
	@SuppressWarnings("unused")
	private AlertDialog getCardInstallAlertDialog(final String coCardNm){
		
		final Hashtable<String, String> cardNm = new Hashtable<String, String>();		
		cardNm.put("HYUNDAE", "현대 앱카드");
		cardNm.put("SAMSUNG", "삼성 앱카드");
		cardNm.put("LOTTE",   "롯데 앱카드");
		cardNm.put("SHINHAN", "신한 앱카드");
		cardNm.put("KB", 	  "국민 앱카드");
		cardNm.put("HANASK",  "하나SK 통합안심클릭");
		//cardNm.put("SHINHAN_SMART",  "Smart �떊�븳�빋");		
		
		final Hashtable<String, String> cardInstallUrl = new Hashtable<String, String>();		
		cardInstallUrl.put("HYUNDAE", "market://details?id=com.hyundaicard.appcard");
		cardInstallUrl.put("SAMSUNG", "market://details?id=kr.co.samsungcard.mpocket");
		cardInstallUrl.put("LOTTE",   "market://details?id=com.lotte.lottesmartpay");
		cardInstallUrl.put("LOTTEAPPCARD",   "market://details?id=com.lcacApp");
		cardInstallUrl.put("SHINHAN", "market://details?id=com.shcard.smartpay");
		cardInstallUrl.put("KB", 	  "market://details?id=com.kbcard.cxh.appcard");
		cardInstallUrl.put("HANASK",  "market://details?id=com.ilk.visa3d");
		//cardInstallUrl.put("SHINHAN_SMART",  "market://details?id=com.shcard.smartpay");//�뿬湲� �닔�젙 �븘�슂!!2014.04.01
		
		AlertDialog alertCardApp =  new AlertDialog.Builder(HomeActivity.this) 
	  		.setIcon(android.R.drawable.ic_dialog_alert) 
	  		.setTitle("알림") 
	  		.setMessage( cardNm.get(coCardNm) + " 어플리케이션이 설치되어 있지 않습니다. \n설치를 눌러 진행 해 주십시요.\n취소를 누르면 결제가 취소 됩니다.") 
	  		.setPositiveButton("설치", new DialogInterface.OnClickListener() { 
	            @Override 
	            public void onClick(DialogInterface dialog, int which) { 
	            	String installUrl = cardInstallUrl.get(coCardNm);
		    		Uri uri = Uri.parse(installUrl);
		    		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		    		Log.d("<INIPAYMOBILE>","Call : "+uri.toString());
		    		try{
		    		 startActivity(intent);	    
		    		}catch (ActivityNotFoundException anfe) {
		            	Toast.makeText(HomeActivity.this, cardNm.get(coCardNm) + "설치 url이 올바르지 않습니다" , Toast.LENGTH_SHORT).show(); 
					}
		    		//finish();	            	
	            } 
	  		}) 
	  		.setNegativeButton("취소", new DialogInterface.OnClickListener() { 			 
	            @Override 
	            public void onClick(DialogInterface dialog, int which) { 
	            	Toast.makeText(HomeActivity.this, "(-1)결제를 취소 하셨습니다." , Toast.LENGTH_SHORT).show(); 
	            	finish(); 
	            } 
	  		})
	  		.create(); 
		
		return alertCardApp;
		
	}//end getCardInstallAlertDialog
	
	    
	protected Dialog onCreateDialog(int id) {//ShowDialog
		
		 
		  switch(id){
		  	  
	  	  	case Global.DIALOG_PROGRESS_WEBVIEW:
			  	ProgressDialog dialog = new ProgressDialog(this);
			  	dialog.setMessage("로딩중입니다. \n잠시만 기다려주세요.");
		        dialog.setIndeterminate(true);
		        dialog.setCancelable(true);
		        return dialog;

			  case Global.DIALOG_PROGRESS_MESSAGE:
				  break;
					
		        
			  case Global.DIALOG_ISP:
				  	
				  alertIsp =  new AlertDialog.Builder(HomeActivity.this) 
				  		.setIcon(android.R.drawable.ic_dialog_alert) 
				  		.setTitle("알림") 
				  		.setMessage("모바일 ISP 어플리케이션이 설치되어 있지 않습니다. \n설치를 눌러 진행 해 주십시요.\n취소를 누르면 결제가 취소 됩니다.") 
				  		.setPositiveButton("설치", new DialogInterface.OnClickListener() { 
				            @Override 
				            public void onClick(DialogInterface dialog, int which) { 
				            	
				            	String ispUrl = "http://mobile.vpay.co.kr/jsp/MISP/andown.jsp"; 
				            	((Pay_Fragment)mFragPayment).wv_pay.loadUrl(ispUrl);
				            	finish();
				            } 
				  		}) 
				  		.setNegativeButton("취소", new DialogInterface.OnClickListener() { 			 
				            @Override 
				            public void onClick(DialogInterface dialog, int which) { 
				            	
				            	Toast.makeText(HomeActivity.this, "(-1)결제를 취소 하셨습니다." , Toast.LENGTH_SHORT).show(); 
				            	finish(); 
				            } 
			 
				  		})
				  		.create(); 
				  	
				  	return alertIsp;
			  
			  case Global.DIALOG_CARDAPP :
				  return getCardInstallAlertDialog(Global.DIALOG_CARDNM);
				  
		   }//end switch
		    
		   return super.onCreateDialog(id);
		   
	}//end onCreateDialog
	
	public void PlaySong(String fullpath, float speed) {
	    Log.d(TAG, "PlaySong... " + fullpath);
	    // float pitch = 1;
	    // float rate = 1;
	    try {

	      if (binder.isPlaying(0)) {
	        binder.stop(0);
	        binder.reset(0);
	      }

	      // support to play next file.
	      binder.setDataSourceString(0, fullpath);
	      binder.prepare(0);
	      binder.start(0);
	      binder.setPlaybackSpeed(0, speed);
	      bMusicComplete = false;
	      bMusicPrepared = false;

	      int iDuration = binder.getDuration(0);
	      ((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.SetPlayTotlaTime(iDuration / 100);

	    } catch (RemoteException e) {
	      Log.e(TAG, "PlaySong, " + e.getMessage());
	    }
	  }
	
	public void PlayStop() {
	    Log.d(TAG, "PlayStop...");
	    
	    
	    try {
	      if (binder.isPlaying(0)) {
	        binder.stop(0);

	        binder.reset(0);
	        // bMusicComplete = true;
	      }
	    } catch (RemoteException e) {
	      Log.e(TAG, "PlayStop, " + e.getMessage());
	    }
	  }

	  public void PlayReset() {
	    Log.d(TAG, "PlayReset...");
	    try {
	      binder.reset(0);
	    } catch (RemoteException e) {
	      Log.e(TAG, "PlayReset, " + e.getMessage());
	    }
	  }

	  public void PlaySpeed(float speed) {
	    Log.d(TAG, "PlaySpeed...");
	    try {
	      if (binder.isPlaying(0)) {
	        binder.setPlaybackSpeed(0, speed);
	      }
	    } catch (RemoteException e) {
	      Log.e(TAG, "PlaySpeed, " + e.getMessage());
	    }
	  }

	  public void PlayPause() {
	    Log.d(TAG, "PlayPause...");
	    try {
	      if (binder.isPlaying(0)) {
	        binder.pause(0);
	      }
	    } catch (RemoteException e) {
	      Log.e(TAG, "PlayPause, " + e.getMessage());
	    }
	  }

	  public void PlayPlay() {
	    Log.d(TAG, "PlayPlay...");
	    try {
	      binder.start(0);
	    } catch (RemoteException e) {
	      Log.e(TAG, "PlayPlay, " + e.getMessage());
	    }
	  }
	
	public void PlaySeek(int seek) {
	    Log.d(TAG, "PlaySeek... " + seek);
	    try {
	      binder.seekTo(0, seek);
	    } catch (RemoteException e) {
	      Log.e(TAG, "PlaySeek, " + e.getMessage());
	    }
	  }
	
	public int GetPlayCurrentPos() {
	    try {
	      if (((ListeningmaxFragment)mFragListeningmax).hMusicPlayer.bPlaySong && !bMusicComplete)
	        return binder.getCurrentPosition(0);
	    } catch (RemoteException e) {
	      Log.e(TAG, "GetPlayCurrentPos, " + e.getMessage());
	    }
	    return 0;
	  }
	
	public void ScreenInfo() {
	    DisplayMetrics displayMetrics = new DisplayMetrics();

	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

	    deviceWidth = displayMetrics.widthPixels;
	    deviceHeight = displayMetrics.heightPixels;

	    Log.d(TAG, "deviceWidth=" + deviceWidth + " , deviceHeight=" + deviceHeight);

	    // 瑗� �꽔�뼱 二쇱뼱�빞 �븳�떎. �씠�젃寃� �빐�빞 displayMetrics媛� �꽭�똿�씠 �맂�떎.
	    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

	    int dipWidth = (int) (120 * displayMetrics.density);
	    int dipHeight = (int) (90 * displayMetrics.density);
	    Log.d(TAG, "dipWidth=" + dipWidth + " , dipHeight=" + dipHeight);
	  }
	
	public void Show_Popup(PopupType type)
	{
		if(type == PopupType.AskSent)
		{
			img_popup_asksent.setVisibility(View.VISIBLE);
			img_popup_payment_complete.setVisibility(View.GONE);
			img_popup_resumesent.setVisibility(View.GONE);
			rlly_popup_yourphone.setVisibility(View.GONE);
			img_popup_request.setVisibility(View.GONE);
			img_popup_network.setVisibility(View.GONE);
			
		}
		else if(type == PopupType.PaymentComplete)
		{
			img_popup_asksent.setVisibility(View.GONE);
			img_popup_payment_complete.setVisibility(View.VISIBLE);
			img_popup_resumesent.setVisibility(View.GONE);
			rlly_popup_yourphone.setVisibility(View.GONE);
			img_popup_request.setVisibility(View.GONE);
			img_popup_network.setVisibility(View.GONE);
		}
		else if(type == PopupType.ResumeSent)
		{
			img_popup_asksent.setVisibility(View.GONE);
			img_popup_payment_complete.setVisibility(View.GONE);
			img_popup_resumesent.setVisibility(View.VISIBLE);
			rlly_popup_yourphone.setVisibility(View.GONE);
			img_popup_request.setVisibility(View.GONE);
			img_popup_network.setVisibility(View.GONE);
		}
		else if(type == PopupType.YourPhone)
		{
			img_popup_asksent.setVisibility(View.GONE);
			img_popup_payment_complete.setVisibility(View.GONE);
			img_popup_resumesent.setVisibility(View.GONE);
			rlly_popup_yourphone.setVisibility(View.VISIBLE);
			img_popup_request.setVisibility(View.GONE);
			img_popup_network.setVisibility(View.GONE);
		}
		else if(type == PopupType.Request)
		{
			img_popup_asksent.setVisibility(View.GONE);
			img_popup_payment_complete.setVisibility(View.GONE);
			img_popup_resumesent.setVisibility(View.GONE);
			rlly_popup_yourphone.setVisibility(View.GONE);
			img_popup_request.setVisibility(View.VISIBLE);
			img_popup_network.setVisibility(View.GONE);
		}
		else if(type == PopupType.NetworkError)
		{
			img_popup_asksent.setVisibility(View.GONE);
			img_popup_payment_complete.setVisibility(View.GONE);
			img_popup_resumesent.setVisibility(View.GONE);
			rlly_popup_yourphone.setVisibility(View.GONE);
			img_popup_request.setVisibility(View.GONE);
			img_popup_network.setVisibility(View.VISIBLE);
		}
		rlly_popup.setVisibility(View.VISIBLE);
		
	}
	
	public void Show_Asksent_Popup()
	{
		
	}
	
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg); 
			
			switch(msg.what)
			{
			case SEND_ASK:
				Show_Popup(PopupType.Request);
				break;
			}
		}
	};
	
	private void SendAsk(String message)
	{
		Log.d(TAG, "SendAsk : " + message);
		
		final String msg = message;
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
				postParameters.add(new BasicNameValuePair("from", Global.naverid + "@naver.com"));
				postParameters.add(new BasicNameValuePair("to", "thankyou@studyview.co.kr"));
				postParameters.add(new BasicNameValuePair("message", msg));
				
				Log.d(TAG, "param : " + postParameters.toString());
            	String result = "";
            	JSONObject resultobject = null;
            	
            	
            	try {
					result = CustomHttpClient.executeHttpPost(Global.clinic_askurl, postParameters);
					
					if(result.equals("")) return;
					Log.d(TAG, "result : " + result);
					resultobject = new JSONObject(result);					
            	}
            	catch(Exception e)
            	{
            		e.printStackTrace();
            	}
            	
            	
            	Message msg = Message.obtain();
				msg.what = SEND_ASK;
				
				handler.sendMessage(msg);
			}
		}).start();
		
	}
	
	private void setDeviceData() {
		// 와이파이 관련.   getSystemService : 인스턴스를 얻음.
  		WifiManager wifiman = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
  		WifiInfo wifiinfo = wifiman.getConnectionInfo();
  		Log.d(TAG, "Index___onCreate 4");
  		
  		TelephonyManager tpman = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
  		//단말기의 디바이스 아이디 추출.
  		//strMacAddress = null;
  		//디바이스 아이디를 사용하지 못하는 경우는 null 을 리턴..
  		if((tpman.getDeviceId() == null) && (wifiinfo.getMacAddress() == null))
  		{
  			Toast.makeText(this, "Not Mobile", Toast.LENGTH_SHORT).show();
  			return;
  		}
  		else
  		{
  			_info.HINT = 0x01; 
  			if(tpman.getDeviceId() != null && tpman.getDeviceId().length() > 0)
  			{
  				_info.HINT = _info.HINT | 0x08;
  				_info.IMEI = tpman.getDeviceId();
  				Log.d(TAG, "Index___Imei : " + _info.IMEI + ", " + _info.IMEI.length());
  			}
  			if(wifiinfo.getMacAddress() != null && wifiinfo.getMacAddress().length() > 0)
  			{
  				_info.HINT = _info.HINT | 0x10;
  				_info.MACADDRESS = wifiinfo.getMacAddress().replaceAll(":", "");
  				Log.d(TAG, "Index___MacAddress : " + _info.MACADDRESS + ", " + _info.MACADDRESS.length());
  			}
 	 	}	
	}
	
	private void startDownload_EdumaxAudio() {
	    String url0 = "http://studyview.co.kr/ms4/bf.MS4";
	    String url1 = "http://studyview.co.kr/ms4/bn.MS4";
	    new AsyncTask<String, String, String>(){
	    	
	    	@Override
	    	protected void onPreExecute() { 
	    		
	    	    
	    	    super.onPreExecute();
	    	}

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				int count = 0;
				
				Global.IsDownloading = true;
			     
			    try {
			    	
			    	for(int i=0; i<2; i++)
			    	{
				        Thread.sleep(10);
				        URL url = new URL(params[i].toString());
				        URLConnection conexion = url.openConnection();
				        conexion.connect();
				        
				        Log.d(TAG, "Download from " + params[i]);
				 
				        int lenghtOfFile = conexion.getContentLength();
				        Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
				 
				        InputStream input = new BufferedInputStream(url.openStream());
				        OutputStream output = new FileOutputStream(Global.ex_storage + "/visangedu/" + (i == 0 ? "bf.MS4" : "bn.MS4"));
				 
				        byte data[] = new byte[1024];
				 
				        long total = 0;
				 
				        while ((count = input.read(data)) != -1) {
				            total += count;
				            
				            
				            publishProgress("progress", "" + (int) ((total * 100) / lenghtOfFile), "" + (i + 1));
				            
				            output.write(data, 0, count);
				        }
				 
				        output.flush();
				        output.close();
				        input.close();
			    	}
			    	
			    	Global.IsDownloading = false;
			         
			    } catch (InterruptedException e) {
			        e.printStackTrace();
			    } catch (IOException e) {
			        e.printStackTrace(); 
			    }
			    finally {
			    	Global.IsDownloading = false;
			    }
			    
			    
			 
			    // 수행이 끝나고 리턴하는 값은 다음에 수행될 onProgressUpdate 의 파라미터가 된다
			    return null;
			}
			
			@Override
			protected void onProgressUpdate(String... progress) {
				
			}
			
			@SuppressWarnings("deprecation")
			@Override
			protected void onPostExecute(String result) {
				
				Global.IsDownloading = false;
				Log.d(TAG, "Download complete");
				
				int nStandardTime = (int)(System.currentTimeMillis() / 1000);
				//int nRtn = TMS4Encrypt.TMS4ERecrypt(downloadDir.getPath() + "/Android_phone.mp4.MS4",
				int nRtn = TMS4Encrypt.TMS4ERecrypt(Environment.getExternalStorageDirectory().getAbsolutePath() + "/visangedu/bf.MS4",
						_info.HINT, _info.IMEI, _info.MACADDRESS, "user", "url", "watermark",
	    				nStandardTime, 30, 0, 7); 
				
				Log.d(TAG, "Recrypt Return : " + nRtn);
				
				String temp = Environment.getExternalStorageDirectory().getAbsolutePath() + "/visangedu/bf.MS4";
				 
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ temp)));
                Log.d(TAG, "미디어스캐닝 완료");

                try {
                     Thread.sleep(2000);
                } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                }
                
                //PlayMedia(temp);
			}
	    	
	    }.execute(url0, url1);
	} 
	

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		
		
		Log.e(TAG, "video act onDestroy");
		if(_webServer != null)
		{
			try {
				_webServer.StopServer();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			_webServer = null;
		}
		
		// (5) final
		
		super.onDestroy();
		
		
	}
	
	
}
